{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# batch-generator-bulur-image-dataset\n",
    "**说明**:批量生成模糊图像数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # test\n",
    "# for root, dirs, files in os.walk(\".\", topdown=False):\n",
    "#     for name in files:\n",
    "#         print(\"\"+os.path.join(root, name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 图像重新编号且图像resize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Image_Resize():\n",
    "    for root, dirs, files in os.walk(\"./一系列bug问题/.\", topdown=False):\n",
    "        i = 0\n",
    "        for name in files:\n",
    "            img=cv2.imread((\"\"+os.path.join(root, name)))\n",
    "            dst=cv2.resize(img,(480,240)) #改变图片尺寸\n",
    "            i = i + 1\n",
    "            cv2.imwrite(\"./重新编号后的数据集/\"+ str(i) + '.bmp',dst)\n",
    "        for name in dirs:\n",
    "            print(os.path.join(root, name))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "./一系列bug问题/./ITF14\n",
      "./一系列bug问题/./MSI无校验（开启一位校验码的时候仍可识读）\n",
      "./一系列bug问题/./CODEBAR\n",
      "./一系列bug问题/./Codebar mod10\n",
      "./一系列bug问题/./msi无校验\n",
      "./一系列bug问题/./mat25\n",
      "./一系列bug问题/./INT25\n",
      "./一系列bug问题/./codebar_1\n"
     ]
    }
   ],
   "source": [
    "d = Image_Resize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 图像增强\n",
    "水平翻转\\竖直翻转\\旋转\\随机剪裁后缩放"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "run_augmentation.py\n",
    "\"\"\"\n",
    "import os\n",
    "import argparse\n",
    "import random\n",
    "import math\n",
    "from multiprocessing import Process\n",
    "from multiprocessing import cpu_count\n",
    "\n",
    "import cv2\n",
    "\n",
    "# 导入image_augmentation.py为一个可调用模块\n",
    "import image_augmentation as ia\n",
    "\n",
    "# # 利用Python的argparse模块读取输入输出和各种扰动参数\n",
    "# def parse_args():\n",
    "#     parser = argparse.ArgumentParser(\n",
    "#         description='A Simple Image Data Augmentation Tool',\n",
    "#         formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n",
    "\n",
    "#     parser.add_argument('input_dir',\n",
    "#                         help='Directory containing images')\n",
    "#     parser.add_argument('output_dir',\n",
    "#                         help='Directory for augmented images')\n",
    "#     parser.add_argument('num',\n",
    "#                         help='Number of images to be augmented',\n",
    "#                         type=int)\n",
    "\n",
    "#     parser.add_argument('--num_procs',\n",
    "#                         help='Number of processes for paralleled augmentation',\n",
    "#                         type=int, default=cpu_count())\n",
    "\n",
    "#     parser.add_argument('--p_mirror',\n",
    "#                         help='Ratio to mirror an image',\n",
    "#                         type=float, default=0.5)\n",
    "\n",
    "#     parser.add_argument('--p_crop',\n",
    "#                         help='Ratio to randomly crop an image',\n",
    "#                         type=float, default=1.0)\n",
    "#     parser.add_argument('--crop_size',\n",
    "#                         help='The ratio of cropped image size to original image size, in area',\n",
    "#                         type=float, default=0.8)\n",
    "#     parser.add_argument('--crop_hw_vari',\n",
    "#                         help='Variation of h/w ratio',\n",
    "#                         type=float, default=0.1)\n",
    "\n",
    "#     parser.add_argument('--p_rotate',\n",
    "#                         help='Ratio to randomly rotate an image',\n",
    "#                         type=float, default=1.0)\n",
    "#     parser.add_argument('--p_rotate_crop',\n",
    "#                         help='Ratio to crop out the empty part in a rotated image',\n",
    "#                         type=float, default=1.0)\n",
    "#     parser.add_argument('--rotate_angle_vari',\n",
    "#                         help='Variation range of rotate angle',\n",
    "#                         type=float, default=10.0)\n",
    "\n",
    "#     parser.add_argument('--p_hsv',\n",
    "#                         help='Ratio to randomly change gamma of an image',\n",
    "#                         type=float, default=1.0)\n",
    "#     parser.add_argument('--hue_vari',\n",
    "#                         help='Variation of hue',\n",
    "#                         type=int, default=10)\n",
    "#     parser.add_argument('--sat_vari',\n",
    "#                         help='Variation of saturation',\n",
    "#                         type=float, default=0.1)\n",
    "#     parser.add_argument('--val_vari',\n",
    "#                         help='Variation of value',\n",
    "#                         type=float, default=0.1)\n",
    "\n",
    "#     parser.add_argument('--p_gamma',\n",
    "#                         help='Ratio to randomly change gamma of an image',\n",
    "#                         type=float, default=1.0)\n",
    "#     parser.add_argument('--gamma_vari',\n",
    "#                         help='Variation of gamma',\n",
    "#                         type=float, default=2.0)\n",
    "\n",
    "#     args = parser.parse_args()\n",
    "#     args.input_dir = args.input_dir.rstrip('/')\n",
    "#     args.output_dir = args.output_dir.rstrip('/')\n",
    "\n",
    "#     return args\n",
    "\n",
    "# '''\n",
    "# 根据进程数和要增加的目标图片数，\n",
    "# 生成每个进程要处理的文件列表和每个文件要增加的数目\n",
    "# '''\n",
    "# def generate_image_list(args):\n",
    "#     # 获取所有文件名和文件总数\n",
    "#     filenames = os.listdir(args.input_dir)\n",
    "#     num_imgs = len(filenames)\n",
    "\n",
    "# \t# 计算平均处理的数目并向下取整\n",
    "#     num_ave_aug = int(math.floor(args.num/num_imgs))\n",
    "\t\n",
    "# \t# 剩下的部分不足平均分配到每一个文件，所以做成一个随机幸运列表\n",
    "# \t# 对于幸运的文件就多增加一个，凑够指定的数目\n",
    "#     rem = args.num - num_ave_aug*num_imgs\n",
    "#     lucky_seq = [True]*rem + [False]*(num_imgs-rem)\n",
    "#     random.shuffle(lucky_seq)\n",
    "\n",
    "# \t# 根据平均分配和幸运表策略，\n",
    "# \t# 生成每个文件的全路径和对应要增加的数目并放到一个list里\n",
    "#     img_list = [\n",
    "#         (os.sep.join([args.input_dir, filename]), num_ave_aug+1 if lucky else num_ave_aug)\n",
    "#         for filename, lucky in zip(filenames, lucky_seq)\n",
    "#     ]\n",
    "\t\n",
    "# \t# 文件可能大小不一，处理时间也不一样，\n",
    "# \t# 所以随机打乱，尽可能保证处理时间均匀\n",
    "#     random.shuffle(img_list)\n",
    "\n",
    "# \t# 生成每个进程的文件列表，\n",
    "# \t# 尽可能均匀地划分每个进程要处理的数目\n",
    "#     length = float(num_imgs) / float(args.num_procs)\n",
    "#     indices = [int(round(i * length)) for i in range(args.num_procs + 1)]\n",
    "#     return [img_list[indices[i]:indices[i + 1]] for i in range(args.num_procs)]\n",
    "\n",
    "# # 每个进程内调用图像处理函数进行扰动的函数\n",
    "# def augment_images(filelist, args):\n",
    "#     # 遍历所有列表内的文件\n",
    "#     for filepath, n in filelist:\n",
    "#         img = cv2.imread(filepath)\n",
    "#         filename = filepath.split(os.sep)[-1]\n",
    "#         dot_pos = filename.rfind('.')\n",
    "\t\t\n",
    "# \t\t# 获取文件名和后缀名\n",
    "#         imgname = filename[:dot_pos]\n",
    "#         ext = filename[dot_pos:]\n",
    "\n",
    "#         print('Augmenting {} ...'.format(filename))\n",
    "#         for i in range(n):\n",
    "#             img_varied = img.copy()\n",
    "\t\t\t\n",
    "# \t\t\t# 扰动后文件名的前缀\n",
    "#             varied_imgname = '{}_{:0>3d}_'.format(imgname, i)\n",
    "\t\t\t\n",
    "# \t\t\t# 按照比例随机对图像进行镜像\n",
    "#             if random.random() < args.p_mirror:\n",
    "# \t\t\t    # 利用numpy.fliplr(img_varied)也能实现\n",
    "#                 img_varied = cv2.flip(img_varied, 1)\n",
    "#                 varied_imgname += 'm'\n",
    "\t\t\t\n",
    "# \t\t\t# 按照比例随机对图像进行裁剪\n",
    "#             if random.random() < args.p_crop:\n",
    "#                 img_varied = ia.random_crop(\n",
    "#                     img_varied,\n",
    "#                     args.crop_size,\n",
    "#                     args.crop_hw_vari)\n",
    "#                 varied_imgname += 'c'\n",
    "\t\t\t\n",
    "# \t\t\t# 按照比例随机对图像进行旋转\n",
    "#             if random.random() < args.p_rotate:\n",
    "#                 img_varied = ia.random_rotate(\n",
    "#                     img_varied,\n",
    "#                     args.rotate_angle_vari,\n",
    "#                     args.p_rotate_crop)\n",
    "#                 varied_imgname += 'r'\n",
    "\t\t\t\n",
    "# \t\t\t# 按照比例随机对图像进行HSV扰动\n",
    "#             if random.random() < args.p_hsv:\n",
    "#                 img_varied = ia.random_hsv_transform(\n",
    "#                     img_varied,\n",
    "#                     args.hue_vari,\n",
    "#                     args.sat_vari,\n",
    "#                     args.val_vari)\n",
    "#                 varied_imgname += 'h'\n",
    "\t\t\t\n",
    "# \t\t\t# 按照比例随机对图像进行Gamma扰动\n",
    "#             if random.random() < args.p_gamma:\n",
    "#                 img_varied = ia.random_gamma_transform(\n",
    "#                     img_varied,\n",
    "#                     args.gamma_vari)\n",
    "#                 varied_imgname += 'g'\n",
    "\t\t\t\n",
    "# \t\t\t# 生成扰动后的文件名并保存在指定的路径\n",
    "#             output_filepath = os.sep.join([\n",
    "#                 args.output_dir,\n",
    "#                 '{}{}'.format(varied_imgname, ext)])\n",
    "#             cv2.imwrite(output_filepath, img_varied)\n",
    "\n",
    "# # 主函数\n",
    "# def main():\n",
    "#     # 获取输入输出和变换选项\n",
    "#     args = parse_args()\n",
    "#     params_str = str(args)[10:-1]\n",
    "\n",
    "# \t# 如果输出文件夹不存在，则建立文件夹\n",
    "#     if not os.path.exists(args.output_dir):\n",
    "#         os.mkdir(args.output_dir)\n",
    "\n",
    "#     print('Starting image data augmentation for {}\\n'\n",
    "#           'with\\n{}\\n'.format(args.input_dir, params_str))\n",
    "\n",
    "# \t# 生成每个进程要处理的列表\n",
    "#     sublists = generate_image_list(args)\n",
    "\t\n",
    "# \t# 创建进程\n",
    "#     processes = [Process(target=augment_images, args=(x, args, )) for x in sublists]\n",
    "\n",
    "# \t# 并行多进程处理\n",
    "#     for p in processes:\n",
    "#         p.start()\n",
    "\n",
    "#     for p in processes:\n",
    "#         p.join()\n",
    "\n",
    "#     print('\\nDone!')\n",
    "\n",
    "# if __name__ == '__main__':\n",
    "#     main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit ('base': conda)",
   "language": "python",
   "name": "python37464bitbasecondacb3ec4d305c44fe887804b43a376a3a9"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
